package com.zjy.heath_ms.interceptor;

import com.zjy.heath_ms.entity.Result;
import com.zjy.heath_ms.utils.JWTUtil;
import com.zjy.heath_ms.utils.JsonUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 项目名 heath_ms
 * 类名  LoginInterceptor
 * 作者 lzq
 * 创建时间  2025/5/10 18:34
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在调用controller之前会调用此方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }
        if (StringUtils.isNoneBlank(token)){
            Claims claims = JWTUtil.checkJWT(token);
            if (claims == null) {
                //token无效
                sendJsonMsg(response, Result.buildFail("登录失败，请重新登录"));
                return false;
            } else {
                int id = Integer.parseInt(claims.get("id").toString());
                String head = (String) claims.get("head");
                String realName = (String) claims.get("realName");
                request.setAttribute("userId", id);
                request.setAttribute("head", head);
                request.setAttribute("realName", realName);
                return true;
            }
        }
        sendJsonMsg(response, Result.buildFail("未登录，请先登录！"));
        return false;
    }

    private void sendJsonMsg(HttpServletResponse response, Object object) {
        try {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(JsonUtil.toJson(object));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
